package sdfi.lee.ReaderFromDisk;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReaderNotice {
	private String filepath=null;
	
	private String content="";
	public ReaderNotice (String filepath)
	{
		
		this.setFilepath(filepath);

	}
	public ReaderNotice(){}
	//initial block
	
	public String getFilepath() {
	
		return filepath;
	}
	public void setFilepath(String filepath) {
		this.filepath = filepath;
		try
		{
			this.readerFormFile();
		}
		catch(Exception ee)
		{
			ee.printStackTrace();
		}
		
	}
	public String getContent() throws Exception  {
		if(this.content==null)
		{	
			this.readerFormFile();
		}
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	
	public void readerFormFile() throws Exception
	{
	
		StringBuffer sf=new StringBuffer();
		File file=new File(this.getFilepath());
		if(!file.exists()) return;
	
		FileInputStream fis=new FileInputStream(this.filepath);
		InputStreamReader isr=new InputStreamReader(fis,"utf-8");
		BufferedReader br=new BufferedReader(isr);
		String line=br.readLine();
		while(line!=null)
		{
			//line=new String(line.getBytes(),"utf-8");
			sf.append(line);
			
			line=br.readLine();
		}
		this.content= sf.toString();
		
	}
	public String getNodeByName(String nodename) throws Exception 
	{
		String name=null;
		if(this.getContent()==null||"".equals(this.getContent()))
				this.readerFormFile();
		if(this.getContent()!=null&&!"".equals(this.getContent()))
		{
			String regex="<"+nodename+">.+</"+nodename+">";
			
			Pattern p=Pattern.compile(regex);
			Matcher matcher=p.matcher(content);
			if(matcher.find())
			{
				name= matcher.group().replace("</"+nodename+">", "")
				.replace("<"+nodename+">", "").trim();
				//name=new String(name.getBytes(),"utf-8");
			}
		}
		
		return name;
	}
}
